package com.bw.gmall.realtime.app.dim;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.app.fun.TableProcessFunction;
import com.bw.gmall.realtime.bean.TableProcess;
import com.bw.gmall.realtime.utils.MyKafkaUtil;
import com.bw.gmall.realtime.utils.MyPhoenixSink;
import com.bw.gmall.realtime.utils.MysqlUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class DimApp {
    public static void main(String[] args) throws Exception {

//        --todo 初始化上下文
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//        // todo 设置并行度
        env.setParallelism(1);
//
//        //TODO 2. 读取kafka主题   topic_db
        String topic = "topic_db";
//
        String groupId = "dimapp";
//
//
//        //测试数据  能不能正常过来
//        //maxwell  （全量）  （增量  脚本一直在开着   只要发生变化就过了）
        DataStreamSource<String> ds = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId));

//        ds.print("maxwell数据：");

//      TODO 3. 过滤非json 数据   保留新增及变化及初始化数据
        SingleOutputStreamOperator<JSONObject> filterJSONDS = ds.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(value);

                    String type = jsonObject.getString("type");

                    if (type.equals("insert") || type.equals("update") || type.equals("bootstrap-insert")) {
                        out.collect(jsonObject);
                    }

                } catch (Exception e) {
                    System.out.println("错误数据不是json格式：" + value);
                }
            }
        });

        //TODO 4. 使用FlinkCDC  读取mysql 配置信息表    创建配置流
        DataStream<String> mysqlDs = MysqlUtil.cdcMysql(env, "gmall_config", "table_process");

//        mysqlDs.print("FlinkCDC:");

        //TODO 5. 将配置流处理为广播流
        MapStateDescriptor<String, TableProcess> mapState = new MapStateDescriptor<>("MapState", String.class, TableProcess.class);

        BroadcastStream<String> broadcastStream = mysqlDs.broadcast(mapState);

        //TODO 6. 连接主流和广播流
        BroadcastConnectedStream<JSONObject, String> connect = filterJSONDS.connect(broadcastStream);


        //TODO 7. 处理连接流   根据配置信息处理主流数据（将配置信息存入到状态中  主流读状态）
        SingleOutputStreamOperator<JSONObject> dimDs = connect.process(new TableProcessFunction());

//        dimDs.print();


//        //TODO 8. 将数据写出到Phoenix
//        dimDs.print("最终结果：----》");
//        dimDs.addSink(new MyPhoenixSink());


        //TODO 9. 启动任务
        env.execute();

    }
}
